import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/order_item_info.dart';
import 'package:app/src/http/bean/wroks/product_bean.dart';
import 'package:app/src/http/bean/wroks/special_clauses.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/a_combined_utils.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../app_ui.dart';

///订单审核条目信息
class UiOrderItemInfo {
  ///List<OrderItemInfo>? 订单条目信息
  ///Product 产品信息
  static Widget build(
      BuildContext context, List<OrderItemInfo>? data, Product? orderInfo,
      {String? title}) {
    if (StringUtils.isEmpty(data) || StringUtils.isEmpty(orderInfo)) {
      return AppUi.getEmptyView();
    }
    List<Widget> children = [];
    if (StringUtils.isEmpty(title)) {
      title = AppStrings.of(context).EntryInformation; //条目信息
    }
    children.add(
        UiBase.title(context, title, bottom: AppEdgeInsets.margin_bottom)); //标题
    children.add(_table(context, data, orderInfo!));
    var column = UiBase.column(context, children);
    var card = UiCard.build(context, column);
    return card;
  }

  static Widget _table(
    BuildContext context,
    List<OrderItemInfo>? data,
    Product orderInfo,
  ) {
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        List<TableRow> children = [];
        //==========================================================================标题
        children.add(TableRow(
            //第一行，添加背景色
            decoration:
                BoxDecoration(color: AppColors.backgroundColorWithTableTitle),
            children: _titles(context, orderInfo)));
        if (data != null && data.length > 0) {
          var postion = 1;
          data.forEach((element) {
            //======================================================================内容
            var cells =
                _contents(context, postion, element, orderInfo, setState);
            postion++;
            children.add(TableRow(children: cells));
            if (element.isOpenAn) {
              //张开，显示二级详情
              element.OrderItemList?.forEach((element) {
                var secondaryContents =
                    _secondaryContents(context, element, orderInfo);
                children.add(TableRow(
                    //二级详情，添加背景色
                    decoration: BoxDecoration(
                        color: AppColors.backgroundColorWithTabelSecondary),
                    children: secondaryContents));
              });
            }
          });
        }

        ///合计
        if (data != null) {
          children.add(TableRow(
              //最后一行，添加背景色
              decoration:
                  BoxDecoration(color: AppColors.backgroundColorWithTableAcom),
              children: _aCombined(context, data!, orderInfo)));
        }
        var table = Table(
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          columnWidths: {
            0: FixedColumnWidth(50),
            1: FixedColumnWidth(50),
          },
          textDirection: TextDirection.ltr,
          border: AppStyle.getTableBorder(),
          children: children,
        );
        var width = 2500.0;
        if (width < px.screenWidth()) {
          width = px.screenWidth();
        }
        return SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          physics: BouncingScrollPhysics(),
          child: Container(
            width: width,
            child: table,
          ),
        );
      },
    );
  }

  ///标题
  static List<Widget> _titles(BuildContext context, Product orderInfo) {
    List<Widget> children = [];
    children.add(_addItem(AppStrings.of(context).Operation)); //操作
    children.add(_addItem(AppStrings.of(context).Entry)); //条目
    children.add(_addItem(AppStrings.of(context).ItemWidth_Customers)); //客户下单宽度
    children
        .add(_addItem(AppStrings.of(context).ItemHeight_Customers)); //客户下单高度
    children.add(_addItem(AppStrings.of(context).ItemWidth + "(mm)")); //宽
    children.add(_addItem(AppStrings.of(context).ItemHeight + "(mm)")); //高
    children.add(_addItem(AppStrings.of(context).ItemNum)); //数量
    children.add(_addItem(AppStrings.of(context).JxArea + "(㎡)")); //矩形面积
    children
        .add(_addItem(AppStrings.of(context).AbnormityTrueArea + "(㎡)")); //实际面积
    children.add(_addItem(AppStrings.of(context).JsArea + "(㎡)")); //结算面积
    children.add(_addItem(AppStrings.of(context).Girth + "(m)")); //周长
    children.add(_addItem(AppStrings.of(context).JxAreaSum + "(m)")); //总面积
    children.add(_addItem(AppStrings.of(context).ItemCode)); //安装编号
    //判断是否打孔
    if (orderInfo.isAdgeSeatType()) {
      children.add(_addItem(AppStrings.of(context).DrillNum)); //打孔数量
    }
    //判断是否挖缺
    if (orderInfo.isDigChipName()) {
      children.add(_addItem(AppStrings.of(context).DigNum)); //挖缺个数
    }
    children.add(_addItem(AppStrings.of(context).SumOtherAmount)); //其他合计/片
    //判断是否大小片
    if (orderInfo.isDistinctSize()) {
      children
          .add(_addItem(AppStrings.of(context).DistinctSizeTypeName)); //错片类型
      children.add(_addItem(AppStrings.of(context).AdgeThree)); //宽左
      children.add(_addItem(AppStrings.of(context).AdgeFour)); //宽右
      children.add(_addItem(AppStrings.of(context).AdgeOne)); //高上
      children.add(_addItem(AppStrings.of(context).AdgeTwo)); //高下
    }
    children.add(_addItem(AppStrings.of(context).OtherAmount)); //另收/片
    children.add(_addItem(AppStrings.of(context).ItemIntro)); //备注
    children.add(_addItem(AppStrings.of(context).ItemGroupCode)); //分组
    children.add(_addItem(AppStrings.of(context).ItemDrawingNo)); //图号
    children.add(_addItem(AppStrings.of(context).ItemDrawingShape)); //图形
    children.add(_addItem(AppStrings.of(context).ItemFile)); //附件
    return children;
  }

  ///内容
  static List<Widget> _contents(BuildContext context, int postion,
      OrderItemInfo element, Product orderInfo, StateSetter setState) {
    List<Widget> children = [];
    if (!element.isOpenAn) {
      children.add(InkWell(
        child: Container(
          alignment: Alignment.center,
          height: 30,
          child: Icon(
            Icons.arrow_drop_down,
            color: Colors.blueAccent,
          ),
        ),
        onTap: () {
          //展开
          setState(() {
            element.isOpenAn = true;
          });
        },
      )); //操作
    } else {
      children.add(InkWell(
        child: Container(
          alignment: Alignment.center,
          height: 30,
          child: Icon(
            Icons.arrow_drop_up,
            color: Colors.blueAccent,
          ),
        ),
        onTap: () {
          //关闭
          setState(() {
            element.isOpenAn = false;
          });
        },
      )); //操作
    }
    children.add(_addItem((postion).toString())); //条目
    children.add(_addItem(element.ItemWidth_Customers)); //客户下单宽度
    children.add(_addItem(element.ItemHeight_Customers)); //客户下单高度
    children.add(_addItem(element.ItemWidth)); //宽
    children.add(_addItem(element.ItemHeight)); //高
    children.add(_addItem(element.ItemNum)); //数量
    children.add(_addItem(element.JxArea)); //矩形面积
    children.add(_addItem(element.AbnormityTrueArea)); //实际面积
    children.add(_addItem(element.JsArea)); //结算面积
    children.add(_addItem(element.Girth)); //周长
    children.add(_addItem(element.JxAreaSum)); //总面积
    children.add(_addItem(element.ItemCode)); //安装编号
    //判断是否打孔
    if (orderInfo.isAdgeSeatType()) {
      children.add(_addItem(element.DrillNum)); //打孔数量
    }
    //判断是否挖缺
    if (orderInfo.isDigChipName()) {
      children.add(_addItem(element.DigNum)); //挖缺个数
    }
    children.add(_addItem(element.SumOtherAmount)); //其他合计/片

    //判断是否大小片
    if (orderInfo.isDistinctSize()) {
      children.add(_addItem(element.DistinctSizeTypeName)); //错片类型
      children.add(_addItem(element.AdgeThree)); //宽左
      children.add(_addItem(element.AdgeFour)); //宽右
      children.add(_addItem(element.AdgeOne)); //高上
      children.add(_addItem(element.AdgeTwo)); //高下
    }
    children.add(_addItem(element.OtherAmount)); //另收/片
    children.add(_addItem(element.ItemIntro)); //备注
    children.add(_addItem(element.ItemGroupCode)); //分组
    children.add(_addItem(element.ItemDrawingNo)); //图号
    children.add(_icon(element.ItemDrawingShape?.getIconUrl(), () {
      element.openImage(context);
    })); //图形
    children
        .add(_addItem(element.getItemFile()?.FileName, isBlue: true, onTap: () {
      element.getItemFile()?.open(context);
    })); //附件
    return children;
  }

  ///二级内容
  static List<Widget> _secondaryContents(
      BuildContext context, OrderItem element, Product orderInfo) {
    List<Widget> children = [];
    children.add(_addItem(element.ItemLayer)); //第几层
    children.add(_addItem("")); //条目
    children.add(_addItem("")); //客户下单宽度
    children.add(_addItem("")); //客户下单高度
    children.add(_addItem(element.ListWidth)); //宽
    children.add(_addItem(element.ListHeight)); //高
    children.add(_addItem("")); //数量
    children.add(_addItem("")); //矩形面积
    children.add(_addItem("")); //实际面积
    children.add(_addItem("")); //结算面积
    children.add(_addItem("")); //周长
    children.add(_addItem("")); //总面积
    children.add(_addItem("")); //安装编号
    //判断是否打孔
    if (orderInfo.isAdgeSeatType()) {
      children.add(_addItem("")); //打孔数量
    }
    //判断是否挖缺
    if (orderInfo.isDigChipName()) {
      children.add(_addItem("")); //挖缺个数
    }
    children.add(_addItem("")); //其他合计/片

    //判断是否大小片
    if (orderInfo.isDistinctSize()) {
      children.add(_addItem("")); //错片类型
      children.add(_addItem("")); //宽左
      children.add(_addItem("")); //宽右
      children.add(_addItem("")); //高上
      children.add(_addItem("")); //高下
    }
    children.add(_addItem("")); //另收/片
    children.add(_addItem("")); //备注
    children.add(_addItem("")); //分组
    children.add(_addItem("")); //图号
    children.add(_addItem("")); //图形
    children.add(_addItem("")); //附件
    return children;
  }

  ///合计
  static List<Widget> _aCombined(
      BuildContext context, List<OrderItemInfo> datas, Product orderInfo) {
    List<Widget> children = [];
    children.add(_addItem(AppStrings.of(context).ACombined)); //合计
    children.add(_addItem("")); //条目
    children.add(_addItem("")); //客户下单宽度
    children.add(_addItem("")); //客户下单高度
    children.add(_addItem("")); //宽
    children.add(_addItem("")); //高
    double ItemNum = 0; //fixme 合计数量
    datas?.forEach((element) {
      var str = element.ItemNum;
      ItemNum = AcombinedUtils.add(ItemNum, str);
    });
    children.add(_addItem(AcombinedUtils.getNum(ItemNum))); //数量
    children.add(_addItem("")); //矩形面积
    double AbnormityTrueArea = 0; //fixme 合计实际面积
    datas?.forEach((element) {
      var str = element.AbnormityTrueArea;
      if (StringUtils.isNotEmpty(str)) {
        try {
          var d = double.parse(str!);
          var mul = AcombinedUtils.multi(d, element.ItemNum); //fixme 需要乘以数量
          AbnormityTrueArea =
              AcombinedUtils.add(AbnormityTrueArea, mul.toString());
        } catch (e) {}
      }
    });
    children.add(_addItem(AcombinedUtils.getArea(AbnormityTrueArea))); //实际面积
    double JsArea = 0; //fixme 合计结算面积
    datas?.forEach((element) {
      var str = element.JsArea;
      if (StringUtils.isNotEmpty(str)) {
        try {
          var d = double.parse(str!);
          var mul = AcombinedUtils.multi(d, element.ItemNum); //fixme 需要乘以数量
          JsArea += mul;
        } catch (e) {}
      }
    });
    children.add(_addItem(AcombinedUtils.getArea(JsArea))); //结算面积
    double Girth = 0; //fixme 合计周长
    datas?.forEach((element) {
      var str = element.Girth;
      if (StringUtils.isNotEmpty(str)) {
        try {
          var d = double.parse(str!);
          var mul = AcombinedUtils.multi(d, element.ItemNum); //fixme 需要乘以数量
          Girth += mul;
        } catch (e) {}
      }
    });
    children.add(_addItem(AcombinedUtils.getPerimeter(Girth))); //周长
    double JxAreaSum = 0; //fixme 合计总面积
    datas?.forEach((element) {
      var str = element.JxAreaSum;
      if (StringUtils.isNotEmpty(str)) {
        try {
          var d = double.parse(str!); //fixme 总面积不需要乘以数量
          JxAreaSum += d;
        } catch (e) {}
      }
    });
    children.add(_addItem(AcombinedUtils.getArea(JxAreaSum))); //总面积
    children.add(_addItem("")); //安装编号
    //判断是否打孔
    if (orderInfo.isAdgeSeatType()) {
      children.add(_addItem("")); //打孔数量
    }
    //判断是否挖缺
    if (orderInfo.isDigChipName()) {
      children.add(_addItem("")); //挖缺个数
    }
    children.add(_addItem("")); //其他合计/片

    //判断是否大小片
    if (orderInfo.isDistinctSize()) {
      children.add(_addItem("")); //错片类型
      children.add(_addItem("")); //宽左
      children.add(_addItem("")); //宽右
      children.add(_addItem("")); //高上
      children.add(_addItem("")); //高下
    }
    children.add(_addItem("")); //另收/片
    children.add(_addItem("")); //备注
    children.add(_addItem("")); //分组
    children.add(_addItem("")); //图号
    children.add(_addItem("")); //图形
    children.add(_addItem("")); //附件
    return children;
  }

  static Widget _addItem(String? text,
      {bool isBlue = false, bool isTrim = true, GestureTapCallback? onTap}) {
    Widget child = Center(child: _text(text, isBlue: isBlue, isTrim: isTrim));
    if (onTap == null) {
      return child;
    }
    return InkWell(
      child: child,
      onTap: onTap,
    );
  }

  static Widget _text(String? text, {bool isBlue = false, bool isTrim = true}) {
    TextStyle? style = null;
    if (isBlue) {
      style = AppStyle.textStyleWithCardBlue();
    } else {
      style = AppStyle.textStyleWithCard();
    }
    String str;
    if (isTrim) {
      str = text?.trim() ?? "";
    } else {
      str = text ?? "";
    }
    return Text(
      str,
      style: style,
    );
  }

  ///小图标显示
  static Widget _icon(String? url, GestureTapCallback? onTap) {
    if (StringUtils.isEmpty(url)) {
      return AppUi.getEmptyView();
    }
    return InkWell(
      child: Image.network(
        url!,
        height: 40,
      ),
      onTap: () {
        onTap?.call();
      },
    );
  }
}
